package com.ruanda.strategy.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruanda.config.WxParamConfig;
import com.ruanda.constant.AuthConstants;
import com.ruanda.domain.LoginMember;
import com.ruanda.mapper.LoginMemberMapper;
import com.ruanda.model.SecurityUser;
import com.ruanda.strategy.LoginStrategy;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

@Service(AuthConstants.MEMBER_LOGIN)
public class MemberLoginStrategy implements LoginStrategy {

    @Autowired
    private WxParamConfig wxParamConfig;
    @Autowired
    private LoginMemberMapper loginMemberMapper;

    /**
     * 编写用户购物车系统会员的登录逻辑
     *
     * @param username
     * @return
     */
    @Override
    public UserDetails realLogin(String username) {
        String realUrl = String.format(wxParamConfig.getUrl(), wxParamConfig.getAppid(), wxParamConfig.getSecret(), username);
        String jsonStr = HttpUtil.get(realUrl);
        if (!StringUtils.hasText(jsonStr)) {
            throw new InternalAuthenticationServiceException("登录异常，请重试");
        }
        // 使用fastjson将登录凭证校验接口响应的json格式的字符串转换为json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        // 获取openid
        String openid = jsonObject.getString("openid");
        // 判断是否有值
        if (!StringUtils.hasText(openid)) {
            throw new InternalAuthenticationServiceException("登录异常,请重试");
        }
        LoginMember loginMember = loginMemberMapper.selectOne(new LambdaQueryWrapper<LoginMember>()
                .eq(LoginMember::getOpenId, openid)
        );
        // 判断会员是否存在
        if (ObjectUtil.isNull(loginMember)) {
            // 会员不存在
            // 注册：创建会员对象到我们的微信小程序的用户体系内
            loginMember = registerMember(openid);
        }
        // 判断会员帐号的状态
        if (!loginMember.getStatus().equals(1)) {
            throw new InternalAuthenticationServiceException("帐号异常，请联系平台工作人员");
        }
        // 说明会员帐号的状态正常
        // 会员存在：返回security框架能够认识的安全用户对象SecurityUser
        SecurityUser securityUser = new SecurityUser();
        securityUser.setUserId(Long.valueOf(loginMember.getId()));
        securityUser.setLoginType(AuthConstants.MEMBER_LOGIN);
        securityUser.setUsername(openid);
        securityUser.setStatus(loginMember.getStatus());
        securityUser.setPassword(wxParamConfig.getPwd());
        securityUser.setOpenId(openid);
        // 根据会员openid查询会员对象
        return securityUser;
    }

    private LoginMember registerMember(String openid) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteAddr();
        LoginMember loginMember = new LoginMember();
        loginMember.setOpenId(openid);
        loginMember.setStatus(1);
        loginMember.setCreateTime(new Date());
        loginMember.setUpdateTime(new Date());
        loginMember.setUserLasttime(new Date());
        loginMember.setUserRegip(ip);
        loginMember.setUserLastip(ip);
        //如果有积分业务
        loginMember.setScore(0);
        //新增会员
        loginMemberMapper.insert(loginMember);
        return loginMember;
    }

    // public static void main(String[] args) {
    //     //springsecurityMd5加密
    //     System.out.println(new BCryptPasswordEncoder().encode("WECHAT"));
    //     //$2a$10$1TbO.SIn9OEm4kKhkkWc9.e152piHBSdu84taDddCr3ikBzjsvjpu
    // }
}